package per.turtle.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import per.turtle.common.core.constant.CommonConstants;
import per.turtle.common.core.constant.UserConstants;
import per.turtle.system.entity.SysMenu;
import per.turtle.system.entity.SysUser;
import per.turtle.system.mapper.SysMenuMapper;
import per.turtle.system.mapper.SysRoleMenuMapper;
import per.turtle.system.service.ISysMenuService;
import per.turtle.system.vo.MetaVo;
import per.turtle.system.vo.RouterVo;
import per.turtle.system.vo.TreeSelect;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 菜单 服务层实现
 *
 * @author turtle
 */
@RequiredArgsConstructor
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {

    private final SysRoleMenuMapper roleMenuMapper;

    @Override
    public List<SysMenu> buildMenuTree(List<SysMenu> menus) {
        List<SysMenu> returnList = new ArrayList<>();
        List<String> tempList = new ArrayList<>();
        for (SysMenu dept : menus) {
            tempList.add(dept.getMenuId());
        }
        for (SysMenu menu : menus) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(menu.getParentId())) {
                recursionFn(menus, menu);
                returnList.add(menu);
            }
        }
        if (returnList.isEmpty()) {
            returnList = menus;
        }
        return returnList;
    }

    @Override
    public List<TreeSelect> buildMenuTreeSelect(List<SysMenu> menus) {
        List<SysMenu> menuTrees = buildMenuTree(menus);
        return menuTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }

    @Override
    public List<RouterVo> buildMenus(List<SysMenu> menus) {
        List<RouterVo> routers = new LinkedList<>();
        for (SysMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden(!menu.getVisible());
            router.setName(getRouteName(menu));
            router.setPath(getRouterPath(menu));
            router.setComponent(getComponent(menu));
            router.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getIsCache()));
            List<SysMenu> cMenus = menu.getChildren();
            if (!cMenus.isEmpty() && UserConstants.TYPE_DIR.equals(menu.getMenuType())) {
                router.setAlwaysShow(true);
                router.setRedirect("noRedirect");
                router.setChildren(buildMenus(cMenus));
            } else if (isMenuFrame(menu)) {
                router.setMeta(null);
                List<RouterVo> childrenList = new ArrayList<>();
                RouterVo children = new RouterVo();
                children.setPath(menu.getPath());
                children.setComponent(menu.getComponent());
                children.setName(StrUtil.upperFirst(menu.getPath()));
                children.setMeta(new MetaVo(menu.getMenuName(), menu.getIcon(), menu.getIsCache()));
                childrenList.add(children);
                router.setChildren(childrenList);
            }
            routers.add(router);
        }
        return routers;
    }

    @Override
    public boolean checkMenuExistRole(String menuId) {
        int result = roleMenuMapper.checkMenuExistRole(menuId);
        return result > 0;
    }

    @Override
    public boolean checkMenuNameUnique(SysMenu menu) {
        QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(StrUtil.isNotBlank(menu.getMenuName()), SysMenu::getMenuName, menu.getMenuName()).eq(SysMenu::getParentId, menu.getParentId());
        wrapper.lambda().ne(menu.getMenuId() != null, SysMenu::getMenuId, menu.getMenuId());
        List<SysMenu> infos = baseMapper.selectList(wrapper);
        return infos.isEmpty();
    }

    @Override
    public int deleteMenuById(String menuId) {
        return baseMapper.deleteById(menuId);
    }

    @Override
    public boolean hasChildByMenuId(String menuId) {
        QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(SysMenu::getParentId, menuId);
        Long result = baseMapper.selectCount(wrapper);
        return result > 0;
    }

    @Override
    public int insertMenu(SysMenu menu) {
        return baseMapper.insert(menu);
    }

    @Override
    public SysMenu selectMenuById(String menuId) {
        return baseMapper.selectById(menuId);
    }

    @Override
    public List<SysMenu> selectMenuList(SysMenu menu, String userId) {
        List<SysMenu> menuList;
        // 管理员显示所有菜单信息
        if (SysUser.isAdmin(userId)) {
            QueryWrapper<SysMenu> wrapper = new QueryWrapper<>(menu);
            wrapper.getEntity().setMenuName(null);
            wrapper.lambda().like(StrUtil.isNotBlank(menu.getMenuName()), SysMenu::getMenuName, menu.getMenuName()).orderByAsc(SysMenu::getParentId)
                   .orderByAsc(SysMenu::getOrderNum);
            menuList = baseMapper.selectList(wrapper);
        } else {
            menu.getParams().put("userId", userId);
            menuList = baseMapper.selectMenuListByUserId(menu);
        }
        return menuList;
    }

    @Override
    public Set<String> selectMenuPermsByUserId(String userId) {
        List<String> perms = baseMapper.selectMenuPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms) {
            if (StrUtil.isNotEmpty(perm)) {
                permsSet.addAll(Arrays.asList(perm.trim().split(StrUtil.COMMA)));
            }
        }
        return permsSet;
    }

    @Override
    public List<SysMenu> selectMenuTreeByUserId(String userId) {
        List<SysMenu> menus;
        if (SysUser.isAdmin(userId)) {
            QueryWrapper<SysMenu> wrapper = new QueryWrapper<>();
            wrapper.lambda().in(SysMenu::getMenuType, UserConstants.TYPE_DIR, UserConstants.TYPE_MENU)
                   .eq(SysMenu::getIsDisabled, CommonConstants.IsDisabled.NORMAL.getValue());
            wrapper.lambda().orderByAsc(SysMenu::getParentId).orderByAsc(SysMenu::getOrderNum);
            menus = baseMapper.selectList(wrapper);
        } else {
            menus = baseMapper.selectMenuTreeByUserId(userId);
        }
        return getChildPerms(menus, "");
    }

    @Override
    public int updateMenu(SysMenu menu) {
        return baseMapper.updateById(menu);
    }

    /**
     * 得到子节点列表
     */
    private List<SysMenu> getChildList(List<SysMenu> list, SysMenu t) {
        List<SysMenu> tList = new ArrayList<>();
        for (SysMenu n : list) {
            if (n.getParentId().equals(t.getMenuId())) {
                tList.add(n);
            }
        }
        return tList;
    }

    private List<SysMenu> getChildPerms(List<SysMenu> list, String parentId) {
        List<SysMenu> returnList = new ArrayList<>();
        for (SysMenu t : list) {
            // 一、根据传入的某个父节点ID,遍历该父节点的所有子节点
            if (t.getParentId().equals(parentId)) {
                recursionFn(list, t);
                returnList.add(t);
            }
        }
        return returnList;
    }

    private String getComponent(SysMenu menu) {
        String component = UserConstants.LAYOUT;
        if (StrUtil.isNotEmpty(menu.getComponent()) && !isMenuFrame(menu)) {
            component = menu.getComponent();
        } else if (StrUtil.isEmpty(menu.getComponent()) && isParentView(menu)) {
            component = UserConstants.PARENT_VIEW;
        }
        return component;
    }

    private String getRouteName(SysMenu menu) {
        String routerName = StrUtil.upperFirst(menu.getPath());
        // 非外链并且是一级目录（类型为目录）
        if (isMenuFrame(menu)) {
            routerName = StrUtil.EMPTY;
        }
        return routerName;
    }

    private String getRouterPath(SysMenu menu) {
        String routerPath = menu.getPath();
        // 非外链并且是一级目录（类型为目录）
        if (StrUtil.isBlank(menu.getParentId()) && UserConstants.TYPE_DIR.equals(menu.getMenuType()) && menu.getIsFrame()) {
            routerPath = "/" + menu.getPath();
        }
        // 非外链并且是一级目录（类型为菜单）
        else if (isMenuFrame(menu)) {
            routerPath = "/";
        }
        return routerPath;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysMenu> list, SysMenu t) {
        return getChildList(list, t).size() > 0;
    }

    /**
     * 是否外链菜单
     *
     * @param menu 菜单
     * @return 是否
     */
    private boolean isMenuFrame(SysMenu menu) {
        return StrUtil.isBlank(menu.getParentId()) && UserConstants.TYPE_MENU.equals(menu.getMenuType()) && menu.getIsFrame();
    }

    private boolean isParentView(SysMenu menu) {
        return StrUtil.isNotBlank(menu.getParentId()) && UserConstants.TYPE_DIR.equals(menu.getMenuType());
    }

    /**
     * 递归列表
     *
     * @param list 菜单列表
     * @param t    菜单
     */
    private void recursionFn(List<SysMenu> list, SysMenu t) {
        // 得到子节点列表
        List<SysMenu> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysMenu tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

}
